#include "head.h"

extern char ip[64];
extern char port[32];
extern char name[64];
extern char token[512];

void* thread_main(void* p){
    shared_resource_t* pshared_resource = (shared_resource_t*)p;
    while(1){
        dowork(pshared_resource);
    }
}

int dowork(shared_resource_t* pshared_resource){
    long_command_t long_command;
    bzero(&long_command, sizeof(long_command));

    pthread_mutex_lock(&(pshared_resource->task_queue_mutex));
    while(pshared_resource->task_queue.size == 0){
        pthread_cond_wait(&(pshared_resource->task_queue_cond), &(pshared_resource->task_queue_mutex));
    }
    de_task_queue(&(pshared_resource->task_queue), &long_command);
    pthread_mutex_unlock(&(pshared_resource->task_queue_mutex));
    

    int socket_fd = 0;
    tcp_init(&socket_fd, ip, port);

    if(strcmp(long_command.command,"puts") == 0){
        //调用puts_handler函数
        puts_handler(socket_fd, long_command);

    }
    else if(strcmp(long_command.command,"gets") == 0){
#if 0        
        puts("进入puts");
        // 测试
        transmit_t transmit;
        bzero(&transmit,sizeof(transmit));
        strcpy(transmit.flag, "LONGCOMMAND");
        strcpy(transmit.token,token);
        strcpy(transmit.command,long_command.command);
        strcpy(transmit.argument,long_command.argument);
        send(socket_fd,&transmit,sizeof(transmit),MSG_NOSIGNAL);
        char buf[1024] = {0};
        recv_train(buf,socket_fd);
        puts(buf);
#endif
         //调用gets_handler函数
         gets_handler(socket_fd, long_command);

    }
    printf("%s@",name);
    fflush(stdout);
    return 0;
}
